<?php
namespace app\install\controller;

use think\Controller;
use tp5_lib\install\logic\Module;
use tp5_lib\install\logic\Monitor;
use DataWidget\widget\ListWidget;
use DataWidget\entity\ActionLink;

/**
 * 模块管理主页
 */
class IndexController extends Controller
{
    public function index()
    {
        $logic=new Module();
        $modules=$logic->getList();

        $module_count=[
            "installed"=>0,
            "available"=>0,
            "fragmentary"=>0,
            "forbidden"=>0,
            "exception"=>0,
        ];
        foreach($modules as $module){
            if(isset($module_count[$module["status"]])){
                $module_count[$module["status"]]++;
            }
            else{
                $module_count[$module["status"]]=1;
            }
        }

        $examine_count=[
            "total"=>0,
            "failed"=>0,
        ];
        foreach($modules as $module){
            if($module["status"] === "installed"){
                $list=$module["examine"];
                foreach($list as $callable){
                    $examine_count["total"]++;
                    if(!call_user_func($callable)){
                        $examine_count["failed"]++;
                    }
                }
            }
        }
        return $this->fetch('',[
            "module"=>$module_count,
            "examine"=>$examine_count,
        ]);
    }
    public function refresh()
    {
        $logic=new Module();
        $logic->getList(true);
        $this->redirect("index");
    }
    public function showModules()
    {
        $logic=new Module();
        $modules=$logic->getList(true);

        foreach($modules as $key => $module){
            $modules[$key]["require_str"]=implode(",",$module["require"]);
        }
        $widget=ListWidget::alloc()
        ->loadFields([
            ["code"=>"id","title"=>"标识"],
            ["code"=>"description","title"=>"简介"],
            ["code"=>"require_str","title"=>"依赖"],
            ["code"=>"status_str","title"=>"状态"],
        ])
        ->setData($modules)
        ->setItemActions(function($item){
            $actions=[];
            $actions[] = ActionLink::create("详情",url('module/index',['module'=>$item["id"]]));
            if($item["status"] === 'installed'){
                $actions[] = ActionLink::create("更新",url('module/update',['module'=>$item["id"]]));
                $actions[] = ActionLink::create("清空",url('module/clear',['module'=>$item["id"]]));
                $actions[] = ActionLink::create("禁用",url('module/forbidden',['module'=>$item["id"]]));
            }
            elseif($item["status"] === 'forbidden'){
                $actions[] = ActionLink::create("解除禁用",url('module/unforbidden',['module'=>$item["id"]]));
            }
            if(in_array($item["status"], ['available','fragmentary'] )){
                $actions[] = ActionLink::create("安装",url('module/install',['module'=>$item["id"]]));
            }
            if($item["status"] !== 'available'){
                $actions[] = ActionLink::create("卸载",url('module/uninstall',['module'=>$item["id"]]));
            }
            $actions[] = ActionLink::create("配置",url('module/config',['module'=>$item["id"]]));
            return $actions;
        })
        ->addFlag("selectable")
        ->toArray();
        return $this->fetch("widget@base/table",[
            "list"=>$widget,
            "entire_actions"=>[
                ActionLink::create("更新",url("updateAll"))->toArray(),
                ActionLink::create("检测",url("examineAll"))->toArray(),
            ],
            "multi_actions"=>[
                ActionLink::create("更新",url("updateAll"))->toArray(),
                ActionLink::create("检测",url("examineAll"))->toArray(),
            ],
        ]);
    }
    public function updateAll()
    {
        /** @var Module $logic */
        $modules=(new Module())->getList();
        foreach($modules as $key => $module){
            if($module["status"] === "installed"){
                $class=$module["logic"];
                $logic=new $class($key,$modules);
                $logic->update();
            }
        }
        $this->success("更新成功");
    }
    public function examineAll()
    {
        $modules=(new Module())->getList();
        $result_list=[];
        $failed=0;
        foreach($modules as $key => $module){
            if($module["status"] === "installed"){
                $list=$module["examine"];
                foreach($list as $callable){
                    $result=[
                        "module"=>$module["id"],
                        "callable"=>$callable,
                        "result"=>call_user_func($callable),
                    ];
                    if($result["result"]===false){
                        $failed++;
                    }
                    $result_list[]=$result;
                }
            }
        }
        print_r($result_list);
        echo "总计执行".count($result_list)."个测试，失败".$failed."个";
        exit;
    }
}
